package com.hengpeng.itfinoss.controller.stm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.CalendarUtil;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.persist.SmsLog;
import com.hengpeng.itfinbase.persist.SmsLog.SmsLogState;
import com.hengpeng.itfinbase.persist.SmsLog.SmsLogTransType;
import com.hengpeng.itfinbase.persist.SmsLog.SmsSendState;
import com.hengpeng.itfinbase.persist.SmsPartner;
import com.hengpeng.itfinbase.persist.SmsPartner.SmsPartnerStatus;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 短息日志控制器
 * </pre>
 * @version 1.0, 2010-9-3
 */
@Controller
@RequestMapping("/sm")
public class SmsLogController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, ModelMap map, String content, String mobile, Integer retryCount,
			String sendTime1, String sendTime2, String sstate, String successTime1, String successTime2, String stype,
			String userId)
	{
		Date sendTimeBegin = null;
		Date sendTimeEnd = null;
		Date successTimeBegin = null;
		Date successTimeEnd = null;
		SmsLogState state = null;
		SmsLogTransType type = null;
		if (sendTime1 != null && sendTime1.trim().length() > 0)
			sendTimeBegin = CalendarUtil.parseFormatNoMM(sendTime1);
		if (sendTime2 != null && sendTime2.trim().length() > 0)
			sendTimeEnd = CalendarUtil.parseFormatNoMM(sendTime2);
		if (successTime1 != null && successTime1.trim().length() > 0)
			successTimeBegin = CalendarUtil.parseFormatNoMM(successTime1);
		if (successTime2 != null && successTime2.trim().length() > 0)
			successTimeEnd = CalendarUtil.parseFormatNoMM(successTime2);
		if (sstate != null && sstate.trim().length() > 0)
			state = SmsLogState.valueOf(sstate);
		if (stype != null && stype.trim().length() > 0)
			type = SmsLogTransType.valueOf(stype);
		map.put("content", content);
		map.put("mobile", mobile);
		map.put("retryCount", retryCount);
		map.put("sendTime1", sendTime1);
		map.put("sendTime2", sendTime2);
		map.put("state", state);
		map.put("successTime1", successTime1);
		map.put("successTime2", successTime2);
		map.put("type", type);
		map.put("userId", userId);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			List<SmsLog> list = new ArrayList<SmsLog>();
			if (mobile != null)
			{
				ServiceResult<List<SmsLog>> result = serviceFactory.getSmsLogService().selectSmsLogPage(content,
						mobile, retryCount, sendTimeBegin, sendTimeEnd, state, successTimeBegin, successTimeEnd, type,
						userId, page.currentPage, page.pageSize, OrderType.DESC, "sendTime");
				page.setEntityCount(result.getReturnListSize());
				list = result.getReturnValue();
			}
			map.put("smsloglist", list);
			map.put("smslogListPage", page);
			return "stm/smslog/smslog_list";
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String preAdd(ModelMap map)
	{
		List<SmsPartner> list = serviceFactory.getSmsService().findAllOpen();
		map.put("list", list);
		map.put("smsLog", new SmsLog());
		return "stm/smslog/detail";
	}

	@RequestMapping(value = "/saveSmsLog", method = RequestMethod.POST)
	public String sendSmsLog(HttpServletRequest request, ModelMap map, String mobile, String content, Long partnerId,
			SmsLogTransType type, String scheduledTime, String fstype, String mobileArr)
	{
		if ("0".equals(fstype))
		{
			// 单条短信发送
			return this.sendSms(request, map, mobile, content, partnerId, type, scheduledTime);
		}
		else
		{
			// 群发短信
			return this.sendSmsArr(request, map, mobileArr, content, partnerId, type, scheduledTime);
		}
	}

	public String sendSms(HttpServletRequest request, ModelMap map, String mobile, String content, Long partnerId,
			SmsLogTransType type, String scheduledTime)
	{
		Date time = null;
		if (scheduledTime != null && !"".equals(scheduledTime))
		{
			try
			{
				time = CalendarUtil.parseFormatNoMM(scheduledTime);
			}
			catch (Exception e)
			{
			}
		}

		SmsPartner partner = serviceFactory.getPersistService().get(SmsPartner.class, partnerId);
		if (partner != null && partner.getStatus() == SmsPartnerStatus.OPEN)
		{
			try
			{
				SmsLog smsLog = this.saveSmsLog(content, mobile, type, time, partner);
				ServiceResult<SmsLog> result = new ServiceResult<SmsLog>(smsLog);
				result.setMessage("发送短信成功");
				return returnSuccess(map, result, "/sm/list");
			}
			catch (Exception e)
			{
				return returnError(map, "发送短信失败！");
			}
		}
		else
		{
			return returnError(map, "短信商户不存在或者未开通！");
		}
	}

	public String sendSmsArr(HttpServletRequest request, ModelMap map, String mobiles, String content, Long partnerId,
			SmsLogTransType type, String scheduledTime)
	{
		Date time = null;
		if (scheduledTime != null && !"".equals(scheduledTime))
		{
			try
			{
				time = CalendarUtil.parseFormatNoMM(scheduledTime);
			}
			catch (Exception e)
			{
			}
		}
		SmsPartner partner = serviceFactory.getPersistService().get(SmsPartner.class, partnerId);
		if (partner != null && partner.getStatus() == SmsPartnerStatus.OPEN)
		{
			String mobileArr[] = mobiles.split("\r");
			if (mobileArr.length > 1000)
			{
				return returnError(map, "只支持一千条以内的短信发送！");
			}
			int cgCount = 0;
			int sbCount = 0;
			for (int i = 0; i < mobileArr.length; i++)
			{
				String mobile = mobileArr[i].replace("\n", "").trim();
				if (mobile.length() == 0)
				{
					continue;
				}
				try
				{
					this.saveSmsLog(content, mobileArr[i], type, time, partner);
					cgCount++;
				}
				catch (Exception e)
				{
					sbCount++;
				}
			}
			ServiceResult<SmsLog> result = new ServiceResult<SmsLog>(new SmsLog());
			result.setMessage("发送短信完成，有" + cgCount + "条成功！" + sbCount + "条失败");
			return returnSuccess(map, result, "/sm/list");
		}
		else
		{
			return returnError(map, "短信商户不存在或者未开通！");
		}
	}

	public SmsLog saveSmsLog(String content, String mobile, SmsLogTransType type, Date time, SmsPartner partner)
	{
		SmsLog smsLog = new SmsLog();
		smsLog.setContent(content);
		smsLog.setMobile(mobile);
		smsLog.setSendPriority(type.getValue());
		if (time != null)
		{
			smsLog.setScheduledTime(time);
			smsLog.setSendState(SmsSendState.SCHEDULED);
		}
		else
		{
			smsLog.setSendState(SmsSendState.IMMEDIATELY);
		}
		smsLog.setState(SmsLogState.WAITING);
		smsLog.setPartnerId(partner.getId());
		smsLog.setSmsSendType(partner.getSmsSendType());
		smsLog = serviceFactory.getPersistService().save(smsLog);
		return smsLog;
	}

	/**
	 * 重发短信
	 * @param ids 需要重发的短信id
	 * @return
	 */
	@RequestMapping(value = "/resend")
	public String reSend(String ids, ModelMap map)
	{
		try
		{
			ResponseMessage response = serviceFactory.getSmsLogService().smsReSend(ids);
			ServiceResult<SmsLog> result = new ServiceResult<SmsLog>();
			result.setCode(response.getRespCode());
			result.setMessage(response.getRespDesc());
			if ("0000".equals(result.getCode()))
			{
				return returnSuccess(map, result, "/sm/list");
			}
			else
			{
				return returnError(map, result.getMessage());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return returnError(map, e);
		}
	}

}
